package com.inkyi.assistant.app.todolist.right;

import com.formdev.flatlaf.FlatLightLaf;
import com.formdev.flatlaf.extras.FlatSVGIcon;
import com.inkyi.assistant.app.todolist.TodoContext;
import com.inkyi.assistant.app.todolist.event.TodoEvent;
import com.inkyi.assistant.app.todolist.event.TodoGroupDTO;
import com.inkyi.assistant.app.todolist.event.TodoRecordDTO;
import com.inkyi.framework.common.utils.CastUtils;
import com.inkyi.framework.daqian.share.border.MLineBorder;
import net.miginfocom.swing.MigLayout;
import org.jdesktop.swingx.JXTextArea;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

public class TodoRightDrawerContent extends JPanel {

    private JButton closeButton;
    private JButton removeButton;
    private JButton saveButton;

    private JCheckBox isFinish;
    private JXTextArea title;

    private JComboBox<GroupComboBox> groupBox;
    private JTextField expireDate;

    private JTextField remind;
    private JTextField repeat;
    private JTextField attachment;
    private JXTextArea remark;
    private volatile Serializable recordId;
    private volatile Serializable groupId;
    private volatile boolean infoInit = false;

    public TodoRightDrawerContent() {
        initComponents();
    }

    public void initComponents() {
        setupUI();
        initConfig();
    }


    private void initConfig() {
        closeButton.addActionListener(e -> {
            TodoContext.getTodoRightPanel().visibleDrawer(false);
            TodoContext.getTodoRightMainContent().clearTodoSelection();
        });
        removeButton.addActionListener(e -> {
            int optionResult = JOptionPane.showConfirmDialog(TodoContext.getTodoRightPanel(), "是否要删除代办？");
            if (optionResult == JOptionPane.OK_OPTION) {
                TodoContext.getEventWrap().fireActionEvent(TodoEvent.of(e.getSource(), TodoEvent.TYPE_RECORD_DEL, recordId));
            }
        });
        saveButton.addActionListener(e -> {
            TodoRecordDTO dto = new TodoRecordDTO();
            dto.setId((Long) recordId);
            dto.setGroupId(getGroupId());
            dto.setFinish(isFinish.isSelected());
            dto.setUpdateTime(LocalDateTime.now());
            dto.setTitle(title.getText());
            TodoContext.getEventWrap().fireActionEvent(TodoEvent.of(e.getSource(), TodoEvent.TYPE_RECORD_SAVE, dto));
        });
        isFinish.addActionListener(e -> {
            JCheckBox source = (JCheckBox) e.getSource();
            boolean isFinish = source.isSelected();
            TodoRecordDTO item = new TodoRecordDTO();
            item.setId((Long) recordId);
            item.setFinish(isFinish);
            TodoContext.getEventWrap().fireActionEvent(TodoEvent.of(e.getSource(), TodoEvent.TYPE_RECORD_FINISH, item));
        });
        groupBox.addItemListener(e -> {
            if (!infoInit) {
                return;
            }
            if (e.getStateChange() == ItemEvent.SELECTED) {
                GroupComboBox selectedItem = CastUtils.cast(e.getItem());
                Long selectGroupId = selectedItem.getId();
                if (Objects.nonNull(selectGroupId) && Objects.equals(groupId, selectGroupId)) {
                    return;
                }
                TodoRecordDTO item = new TodoRecordDTO();
                item.setId((Long) recordId);
                item.setGroupId(selectGroupId);
                TodoContext.getEventWrap().fireActionEvent(TodoEvent.of(e.getSource(), TodoEvent.TYPE_RECORD_SAVE, item));
                groupId = selectGroupId;
            }
        });
    }

    private void setupUI() {
        this.setLayout(new MigLayout("", "", ""));
        this.setBorder(new MLineBorder(Color.DARK_GRAY, 1, true, false, false, false));

        // 头部按钮
        closeButton = new JButton(new FlatSVGIcon("icons/todolist/close.svg", 14, 14));
        closeButton.setToolTipText("关闭");
        closeButton.setBackground(null);
        closeButton.setBorder(null);

        removeButton = new JButton(new FlatSVGIcon("icons/todolist/shanchu.svg", 14, 14));
        removeButton.setToolTipText("删除");
        removeButton.setBackground(null);
        removeButton.setBorder(null);

        saveButton = new JButton(new FlatSVGIcon("icons/todolist/baocun.svg", 14, 14));
        saveButton.setToolTipText("保存");
        saveButton.setBackground(null);
        saveButton.setBorder(null);

        this.add(closeButton, "split 4");
        this.add(saveButton);
        this.add(new JPanel(), "span, pushx, growx");
        this.add(removeButton, "wrap");
        this.add(new JSeparator(), "span, pushx, growx, wrap");

        // 标题
        isFinish = new JCheckBox();
        title = new JXTextArea();
        this.add(isFinish, "split 2");
        this.add(title, "span, pushx, growx, wrap");
        this.add(new JSeparator(), "span, pushx, growx, wrap");

        // 分类
        groupBox = new JComboBox<>();
        this.add(new JLabel("分类"), "split 2, sg 1");
        this.add(groupBox, "wrap");
        this.add(new JSeparator(), "span, pushx, growx, wrap");

        // 到期日
        expireDate = new JTextField();
        this.add(new JLabel("到期日"), "split 2, sg 1");
        this.add(expireDate, "span, pushx, growx, wrap");
        this.add(new JSeparator(), "span, pushx, growx, wrap");

        // 提醒
        remind = new JTextField();
        this.add(new JLabel("提醒"), "split 2, sg 1");
        this.add(remind, "span, pushx, growx, wrap");
        this.add(new JSeparator(), "span, pushx, growx, wrap");

        // 重复
        repeat = new JTextField();
        this.add(new JLabel("重复"), "split 2, sg 1");
        this.add(repeat, "span, pushx, growx, wrap");
        this.add(new JSeparator(), "span, pushx, growx, wrap");

        // 附件
        attachment = new JTextField();
        this.add(new JLabel("附件"), "split 2, sg 1");
        this.add(attachment, "span, pushx, growx, wrap");
        this.add(new JSeparator(), "span, pushx, growx, wrap");

        // 备注
        remark = new JXTextArea();
        remark.setRows(5);
        this.add(new JLabel("备注"), "split 2, sg 1");
        this.add(remark, "span, pushx, growx, wrap");
    }

    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel(new FlatLightLaf());
        } catch (Exception ex) {
            System.err.println("Failed to initialize LaF");
        }

        TodoRightDrawerContent contentPane = new TodoRightDrawerContent();
        JFrame frame = new JFrame();
        frame.setSize(800, 600);
        frame.setContentPane(contentPane);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    public void setInfo(TodoRecordDTO recordDTO, List<TodoGroupDTO> groupList) {
        clearInfo();
        isFinish.setSelected(recordDTO.getFinish());
        title.setText(recordDTO.getTitle());
        expireDate.setText(recordDTO.getDeadline());
        remind.setText(recordDTO.getReminderTime());
        repeat.setText(recordDTO.getRepeatRule());
        remark.setText(recordDTO.getContent());
        this.recordId = recordDTO.getId();
        this.groupId = recordDTO.getGroupId();
        this.groupBox.removeAllItems();
        for (TodoGroupDTO dto : groupList) {
            GroupComboBox comboBox = new GroupComboBox();
            comboBox.setId(dto.getId());
            comboBox.setTitle(dto.getTitle());
            groupBox.addItem(comboBox);
        }
        for (int i = 0; i < groupBox.getItemCount(); i++) {
            GroupComboBox comboBox = groupBox.getItemAt(i);
            if (Objects.equals(comboBox.getId(), groupId)) {
                groupBox.setSelectedIndex(i);
                break;
            }
        }
        infoInit = true;
    }

    private void clearInfo() {
        recordId = null;
        groupId = null;
        infoInit = false;
        isFinish.setSelected(false);
        title.setText("");
        groupBox.removeAllItems();
        expireDate.setText("");
        remind.setText("");
        repeat.setText("");
        attachment.setText("");
        remark.setText("");
    }

    public Long getGroupId() {
        GroupComboBox item = (GroupComboBox) groupBox.getSelectedItem();
        if (item != null) {
            return item.getId();
        }
        return null;
    }
}
